#include "netheader.h"
#include "logqueue.h"
#include <QDebug>
#include <time.h>
#include <stdarg.h>
#include <stdio.h>
#include <QString>

LogQueue *logqueue = nullptr;

QUEUE_DATA<MESG> queue_send;
QUEUE_DATA<MESG> queue_recv;
QUEUE_DATA<MESG> audio_recv;

void log_print(const char *filename, const char *funcname, int line, const char *fmt, ...){
    Log *log = (Log *)malloc(sizeof(Log));
    if(!log)
        qDebug() << "maloc log failed";
    else{
        memset(log, 0, sizeof(Log));
        log->ptr = (char *)malloc(1 * KB);
        if(log->ptr == nullptr){
            free(log);
            //qDebug() << "malloc log.ptr fail";
            return ;
        }else{
            memset(log->ptr, 0, 1 * KB);
            time_t t = time(NULL);
            int pos = 0;
            int m = strftime(log->ptr + pos, KB - 2 -pos, "%Y-%m-%d %H:%M:%S ", localtime(&t));
            pos += m;
            //qDebug() << "timelen_m = " << m;

            m = snprintf(log->ptr + pos, KB - 2 - pos, "%s:%s::%d>>>", filename, funcname, line);
            //qDebug() << "infolen_m = " << m;
            pos += m;

            va_list ap;
            va_start(ap, fmt);
            m = vsnprintf(log->ptr + pos, KB - 2 - pos, fmt, ap);
            qDebug() << "arglen_m = " << m;

            pos += m;
            va_end(ap);
            strcat_s(log->ptr + pos, KB - pos, "\n");
            log->len = strlen(log->ptr);
            //qDebug() << "log->len = " << log->len;
            qDebug() << QString::fromUtf8(log->ptr);
            logqueue->pushLog(log);
        }
    }
}
